package com.licq.kafka.demo.service;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.licq.kafka.demo.constants.KafkaTopicConstant;
import com.licq.kafka.demo.model.Message;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.concurrent.atomic.AtomicLong;

@Component
@Slf4j
public class KafkaProducer {

    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;

    private Gson gson = new GsonBuilder().create();

    AtomicLong atomicLong = new AtomicLong(0L);

    public void send() {
        Message message = new Message();
        message.setId(System.currentTimeMillis());
        message.setMsg("中国崛起:"+atomicLong.incrementAndGet());
        message.setSendTime(new Date());
        log.info("+++++++++++++++++++++send  message = {}", gson.toJson(message));
        kafkaTemplate.send(KafkaTopicConstant.testTopicName, message.getId().toString() ,gson.toJson(message));
    }


    public void send(final String msg) {
        Message message = new Message();
        message.setId(System.currentTimeMillis());
        message.setMsg(msg);
        message.setSendTime(new Date());
        log.info("+++++++++++++++++++++send  message = {}", gson.toJson(message));
        kafkaTemplate.send(KafkaTopicConstant.testTopicName, message.getId().toString() , gson.toJson(message));
    }
}
